package api

import (
	"fmt"
	"gin_cookie/internal/config"
	"gin_cookie/internal/domain/service"
	"log"
	"net/http"
)
import "github.com/gin-gonic/gin"

func Start() {

	fmt.Println("🎯🎯🎯启动服务...")
	// 声明单例
	cookieManager := config.CookieInstance()

	r := gin.Default()

	r.GET("/login", func(c *gin.Context) {
		//c.DefaultQuery("", "")
		userName := c.Query("userName")
		passWord := c.Query("passWord")
		// 登录方法
		flag, err := service.NewSysUserService().Login(userName, passWord)
		if err != nil || flag == false {
			c.JSON(http.StatusInternalServerError, ErrWithMsg(err.Error()))
			return
		}

		// 可以登录发放cookie
		// 由于cookie 不能重复生成先校验 cookie
		val, falg := cookieManager.CheckCooKey(userName)
		if falg == false {
			// 不存在
			var cookieVal string = cookieManager.Generate(userName, 3600, c)
			c.JSON(http.StatusOK, OkWithData(cookieVal))
			log.Printf("用户:%s，cookie不存在,生成cookie", userName)
			return
		}

		c.JSON(http.StatusOK, OkWithData(val))
	})

	// 查看cookie 数量
	r.GET("/cookie", func(c *gin.Context) {
		c.JSON(http.StatusOK, OkWithData(cookieManager.Count()))
	})

	// 受保护的路由
	// 请求头中要携带参数：auth_cookie
	auth := r.Group("/")
	auth.Use(AuthMiddleware())
	{
		auth.GET("/test1", func(c *gin.Context) {
			c.JSON(http.StatusOK, OkWithData(nil))
		})

		auth.GET("/test2", func(c *gin.Context) {
			c.JSON(http.StatusOK, OkWithData(nil))
		})

	}
	// 启动
	r.Run(":60000")

}

// 验证登录状态中间件
func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 从请求headers中获取参数：auth_cookie
		authCookie := c.GetHeader("auth_cookie")
		if authCookie == "" {
			c.JSON(401, ErrWithMsg("未登录!"))
			c.Abort()
			return
		}

		cookieManager := config.CookieInstance()
		// 验证 session 有效性
		if _, flag := cookieManager.CheckExist(authCookie, c); flag == false {
			c.JSON(401, ErrWithMsg("会话已过期!"))
			c.Abort()
			return
		}

		// 将用户信息存储到上下文
		//c.Set("user_id", getUserIDBySession(sessionID))
		c.Next()
	}
}
